#include <cstdio>
#include <cstring>
#include <mysql/mysql.h>

#define HOST "127.0.0.1"
#define USER "root"
#define PASS "15206962723Li"
#define DBNAME "gobang"
#define PORT 3306

int main()
{
    // 初始化句柄
    MYSQL *mysql = mysql_init(NULL);
    if (mysql == nullptr)
    {
        printf("mysql init failed\n");
        return -1;
    }

    // 连接服务器
    if (mysql_real_connect(mysql, HOST, USER, PASS, DBNAME, PORT, nullptr, 0) == nullptr)
    {
        printf("connect mysql error: %s\n", mysql_error(mysql));
        mysql_close(mysql);
        return -1;
    }

    // 设置客户端字符集
    if (mysql_set_character_set(mysql, "utf8") != 0)
    {
        printf("set client character error: %s\n", mysql_error(mysql));
        mysql_close(mysql);
        return -1;
    }

    // mysql_select_db(mysql, DBNAME);

    // 执行mysql语句
    // const char *sql = "insert into stu values(null, '小明', 18, 53, 68, 87);";
    // const char *sql = "update stu set ch=66 where sn=1;";
    // const char *sql = "delete from stu where sn=1;";
    const char *sql = "select * from stu;";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        printf("mysql query error: %s\n", mysql_error(mysql));
        mysql_close(mysql);
        return -1;        
    }

    // 保存查询结果
    MYSQL_RES *res = mysql_store_result(mysql);
    if (res == nullptr)
    {
        mysql_close(mysql);
        return -1;            
    }

    // 获取查询结果
    int num_row = mysql_num_rows(res);
    int num_col = mysql_num_fields(res);

    for (int i = 0; i < num_row; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for (int j = 0; j < num_col; j++)
        {
            printf("%s\t", row[j]);
        }
        printf("\n");
    }

    // 释放结果集
    mysql_free_result(res);

    mysql_close(mysql);
    return 0;
}